# 1. 变量和数据类型
name = "Alice"
age = 25
height = 1.68
is_student = True

# 2. 控制流（if-else, for, while）
if age > 18:
    print(f"{name} is an adult.")
else:
    print(f"{name} is a minor.")

for i in range(5):
    print(f"Loop iteration {i}")

count = 0
while count < 3:
    print(f"While loop iteration {count}")
    count += 1

# 3. 列表、字典、集合和元组
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print("Fruits:", fruits)

person = {"name": "Alice", "age": 25, "is_student": True}
print("Person info:", person)

unique_numbers = {1, 2, 3, 4, 4, 5}
print("Unique numbers:", unique_numbers)

coordinates = (10, 20)
print("Coordinates:", coordinates)

# 4. 函数
def greet(name):
    return f"Hello, {name}!"

print(greet("Bob"))

# 5. 类与面向对象编程
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        raise NotImplementedError("Subclass must implement this method")

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak())
print(cat.speak())

# 6. 文件操作
with open("example.txt", "w") as file:
    file.write("Hello, this is a file example.")

with open("example.txt", "r") as file:
    content = file.read()
    print("File content:", content)

# 7. 异常处理
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("Execution completed.")

# 8. 模块导入
import math
print("Square root of 16:", math.sqrt(16))

from datetime import datetime
print("Current time:", datetime.now())

# 9. 列表推导式
squares = [x**2 for x in range(10)]
print("Squares:", squares)

# 10. 生成器
def fibonacci(limit):
    a, b = 0, 1
    while a < limit:
        yield a
        a, b = b, a + b

print("Fibonacci sequence:")
for num in fibonacci(20):
    print(num, end=" ")
print()

# 11. 装饰器
def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

# 12. Lambda 函数
multiply = lambda x, y: x * y
print("Multiplication:", multiply(3, 4))

# 13. 上下文管理器（with 语句）
class ManagedFile:
    def __init__(self, filename):
        self.filename = filename

    def __enter__(self):
        self.file = open(self.filename, "w")
        return self.file

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()

with ManagedFile("managed_file.txt") as file:
    file.write("This is a managed file.")

# 14. 迭代器和可迭代对象
class Counter:
    def __init__(self, low, high):
        self.current = low
        self.high = high

    def __iter__(self):
        return self

    def __next__(self):
        if self.current > self.high:
            raise StopIteration
        else:
            self.current += 1
            return self.current - 1

print("Counter iterator:")
for num in Counter(1, 5):
    print(num, end=" ")
print()

# 15. 多线程
import threading

def print_numbers():
    for i in range(5):
        print(f"Number: {i}")

thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()

# 16. 正则表达式
import re
text = "The rain in Spain"
pattern = r"\bS\w+"
matches = re.findall(pattern, text)
print("Words starting with 'S':", matches)

# 17. 数据序列化（JSON）
import json
data = {"name": "Alice", "age": 25}
json_string = json.dumps(data)
print("JSON string:", json_string)

loaded_data = json.loads(json_string)
print("Loaded data:", loaded_data)

# 18. 时间和日期
from datetime import timedelta
now = datetime.now()
one_week_later = now + timedelta(weeks=1)
print("One week later:", one_week_later)

# 19. 枚举
from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

print("Color enum:", Color.RED)

# 20. 类型注解
def add(a: int, b: int) -> int:
    return a + b

print("Type annotation example:", add(2, 3))